package com.it13.utils.sendemail;

import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SimpleMailSender {

	/**
	 * 
	 * @param to 
	 * @param cc 
	 * @param subject 
	 * @param body 
	 * @param attchFile 
	 */
	/**
	 * 发送HTML格式的邮件
	 * @param host			主服务器
	 * @param port			端口
	 * @param username		账号
	 * @param password		密码
	 * @param fromaddress	发件人
	 * @param to			收件人 
	 * @param cc			抄送人
	 * @param subject		邮件主题
	 * @param body			邮件内容
	 * @param attchFile		附件  文件路径
	 * @return    
	 * @author yzChen  cyzshenzhen@163.com
	 * @date 2013-10-11 下午8:32:33
	 */
	public synchronized int sendHTMLEmail(String host, String port, String username, String password,
			String fromaddress, String to, String cc, String subject, String body, String attchFile) {
		// 初始化发件人信息
		MailSenderInfo mailinfo = new MailSenderInfo();
		mailinfo.setMailServerHost(host);
		mailinfo.setMailServerPort(port);
		mailinfo.setUserName(username);
		mailinfo.setPassword(password);
		mailinfo.setFromAddress(fromaddress);
		
		int successFlag = 0;
		try {
			Properties props = System.getProperties(); // Properties用来将props传给MAIL

			Session session; // 创建Session对象
			props.put("mail.smtp.host", mailinfo.getMailServerHost());

			if (mailinfo.isValidate()) {
				props.put("mail.smtp.auth", "true");
				session = Session.getInstance(props,
						new MyAuthenticator(mailinfo.getUserName(), mailinfo.getPassword()));
			} else {
				props.put("mail.smtp.auth", "");

				session = Session.getInstance(props, null);
			}

			if (mailinfo.isRestFlag()) {
				session.setDebug(true);
			}
			/** 创建邮件MESSAGE */
			props.put("mail.smtp.sendpartial", mailinfo.getSendpartial());
			Message mesg = new MimeMessage(session);
			InternetAddress[] addresses;

			/** from 地址列表 */
			if (mailinfo.getFromAddress() != null && !mailinfo.getFromAddress().equals("")) {
				mesg.setFrom(new InternetAddress(mailinfo.getFromAddress()));
			} else {
				System.out.println("请填写发信人地址");
				return -2;
			}

			/** TO地址列表 */
			if (to != null && !to.equals("")) {
				addresses = InternetAddress.parse(to);
				mesg.setRecipients(javax.mail.Message.RecipientType.TO, addresses);
			} else {
				System.out.println("请填写收信人地址");
				return -3;
			}
			/** CC地址列表 抄送*/
			if (cc != null && !cc.equals("")) {
				addresses = InternetAddress.parse(cc);
				mesg.setRecipients(javax.mail.Message.RecipientType.CC, addresses);
			}

			/** 设置邮件主题topic */
			if (subject != null && !subject.equals("")) {
				mesg.setSubject(MimeUtility.encodeText(subject,"utf-8","B"));
			} else {
				mesg.setSubject(subject);
				System.out.println("请填写邮件主题");
			}

			/** 设置邮件内容 */
			if (attchFile == null || attchFile.equals("")) {
				//MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象   
				Multipart mainPart = new MimeMultipart();
				// 创建一个包含HTML内容的MimeBodyPart   
				BodyPart html = new MimeBodyPart();
				// 设置HTML内容   
				html.setContent(body, "text/html; charset=utf-8");
				mainPart.addBodyPart(html);
				// 将MiniMultipart对象设置为邮件内容   
				mesg.setContent(mainPart);

				//mesg.setText(body);
			} else {
				//			    MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象   
				Multipart mp = new MimeMultipart();
				//				 创建一个包含HTML内容的MimeBodyPart   
				MimeBodyPart html = new MimeBodyPart();
				html.setContent(body, "text/html; charset=utf-8");
				mp.addBodyPart(html);
				/** 添加附件 */
				ArrayList<String> attachlist = tokenize(attchFile);
				for (int i = 0; i < attachlist.size(); i++) {
					MimeBodyPart attachMbp = new MimeBodyPart();
					FileDataSource fds = new FileDataSource((String) (attachlist.get(i)));
					attachMbp.setDataHandler(new DataHandler(fds));
					attachMbp.setFileName(MimeUtility.encodeText(fds.getName(), "GBK", "B"));
					attachMbp.setHeader("Content-Type", fds.getContentType());
					mp.addBodyPart(attachMbp);
				}
				mesg.setContent(mp);
				//	mesg.setText(body);
			}

			/** 设置邮件发送时间 */
			mesg.setSentDate(new Date());
			/** 发送邮件 */
			if (mailinfo.isValidate()) {
				Transport tr = session.getTransport("smtp");
				tr.connect(mailinfo.getMailServerHost(), mailinfo.getUserName(), mailinfo.getPassword());
				mesg.saveChanges();
				tr.sendMessage(mesg, mesg.getAllRecipients());
				tr.close();
			} else {
				Transport.send(mesg);
			}
		}
		/* send发送邮件的异常处理 */
		catch (SendFailedException e) {
			String str = "";
			if (e.getInvalidAddresses().length > 0) {
				for (Address add : e.getInvalidAddresses()) {
					str += add.toString() + ",";
				}
			}
			System.out.println(str);
		} catch (Exception e) {
			System.out.println("邮件发送失败！");
			successFlag = -9;
			e.printStackTrace();
		}
		return successFlag;
	}

	private ArrayList<String> tokenize(String s) {
		ArrayList<String> arrayl = new ArrayList<String>();
		for (StringTokenizer stringtok = new StringTokenizer(s, ","); stringtok.hasMoreTokens(); arrayl.add(stringtok
				.nextToken().trim()))
			;
		return arrayl;
	}

}
